package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.BaseException;
import com.sky.mapper.UserLoginMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserLoginService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserLoginServiceImpl implements UserLoginService {

    private static final String WX_LOGIN_URL = "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserLoginMapper userLoginMapper;
    @Autowired
    private WeChatProperties weChatProperties;

    /**
     * 微信登录
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {

        //一、调用微信端接口获得用户唯一标识openid
        HashMap<String, String> userMap = new HashMap();
        userMap.put("appid", weChatProperties.getAppid());
        userMap.put("secret", weChatProperties.getSecret());
        userMap.put("js_code", userLoginDTO.getCode());
        userMap.put("grant_type", "authorization_code");
        String json = HttpClientUtil.doGet(WX_LOGIN_URL, userMap);

        //解析json并拿到openid
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");

        //判断是否登录成功
        if(openid == null){
            new BaseException("微信登录失败");
        }

        //二、查询数据库中是否有该openid的用户数据
        User user = userLoginMapper.findByOpenid(openid);
        if(user == null){
            user = new User();
            user.setOpenid(openid);
            user.setCreateTime(LocalDateTime.now());
            //二、存储数据（..\openid）到数据库中并获得主键id
            userLoginMapper.insert(user);
        }
        //三、构建token令牌
        Map<String, Object> claims = new HashMap();
        claims.put("userId", user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(),jwtProperties.getUserTtl(),claims);
        //四、构建返回前端的结果实例
        return UserLoginVO.builder()
                .id(user.getId())
                .token( token)
                .openid(openid)
                .build();
    }
}
